
package com.xudm.cdg.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONFactory;
import com.alibaba.fastjson2.JSONWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.lang.Nullable;

import java.nio.charset.StandardCharsets;

/**
 * FastJson2JsonRedisSerializer
 *
 * @param <T>
 */
@Slf4j
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
    private final Class<T> type;


    static {
        // fastjson升级文档 https://github.com/alibaba/fastjson2/wiki/fastjson_1_upgrade_cn
        // ParserConfig添加autoType白名单的功能在ObjectReaderProvider中提供，可以如下的方式配置autoType白名单
        JSONFactory.getDefaultObjectReaderProvider().addAutoTypeAccept("com.xwtec.cmttg");
    }

    public FastJson2JsonRedisSerializer(Class<T> type) {
        this.type = type;
    }

    @Override
    public T deserialize(@Nullable byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        } else {
            try {
                String str = new String(bytes, StandardCharsets.UTF_8);
                return JSON.parseObject(str, type);
            } catch (Exception var3) {
                throw new SerializationException("Could not read JSON: " + var3.getMessage(), var3);
            }
        }
    }

    @Override
    public byte[] serialize(@Nullable Object t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        } else {
            try {
                return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(StandardCharsets.UTF_8);
            } catch (Exception var3) {
                throw new SerializationException("Could not write JSON: " + var3.getMessage(), var3);
            }
        }
    }
}
